﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebBanThuoc.DAO;
using WebBanThuoc.DTO;
using WebBanThuoc.Server;
using System.Globalization;

namespace WebBanThuoc
{
    public partial class GioHang : System.Web.UI.Page
    {
        IServerWeb sw = new ServerWeb();
        

        protected void Page_Load(object sender, EventArgs e)
        {
            //gán giá trị mặc định cho các field trong form để tránh Causevalidate
            if (!IsPostBack)
            {
                kh_ten.Text = "abc";
               // kh_email.Text = "abc@gmail.com";
                kh_address.Text = "123 LCT Q3";
                kh_phone.Text = "1234567";
                kh_ghichu.InnerText = "abc";
                ghiChu1.InnerText = "abc";
                bt_muahangnhanh.Enabled = true;
                bt_muahang.Enabled = true;
            }

            Session.Add("vi", "hidden");
            Session.Add("vi_kq", "hidden");
            if (Session["kh"] != null)
            {
                resetData1();
                bt_muahangnhanh.Enabled = false;
                if (Session["dis"] != null)  //đã nhấn nút mua hàng có đăng nhập
                {
                    bt_capnhat.Enabled = false;
                    bt_them.Enabled = false;
                }
                KhachHang kh = (KhachHang)Session["kh"];
                Session.Add("kh", kh);
            }
            string maSanPham = "";
            if (Session["maSanPham"] != null)
                maSanPham = Session["maSanPham"].ToString();
            
            List<SanPhamMua> gioHang = null;
            int soSP = 0;
            if (Session["gioHang"] == null)
            {
                gioHang = new List<SanPhamMua>();
                Session.Add("gioHang", gioHang);
            }
            else
            {
                gioHang = (List<SanPhamMua>)Session["gioHang"];
                soSP = Convert.ToInt32(Session["soSP"]);
            }
            SanPhamMua_DAO daoSP = new SanPhamMua_DAO(sw.Connection);
            bool kq = false;
            SanPhamMua s = null;
            if (maSanPham != "")
            {
                for (int i = 0; i < gioHang.Count; i++)
                {
                    s = gioHang[i];
                    if (maSanPham == s.MaSanPham)
                    {
                        s.SoLuong = s.SoLuong + 1;
                        soSP = s.SoLuong;
                        kq = true;
                        break;
                    }
                }
                if (kq == false)
                {
                    s = daoSP.getByKey(maSanPham);
                    s.SoLuong = 1;
                    gioHang.Add(s);
                    soSP++;
                }
            }
           
            
            string action = "";
            if (Request.QueryString["action"] != null)
                action = Request.QueryString["action"];
            if (action != "")
            {
                if (action == "Xoa")
                {
                    maSanPham=Request.Params["maSanPham"].ToString();
                    for (int i = 0; i < gioHang.Count; i++)
                    {
                        SanPhamMua sp = gioHang[i];
                        if (maSanPham == sp.MaSanPham)
                        {
                            soSP = soSP - sp.SoLuong;
                            gioHang.Remove(sp);
                            break;
                        }
                    }
                } //end of if (action == "Xoa")

            } //action!=""

            //cập nhật Tổng Tiền
            int tongTien = 0;
            for (int i = 0; i < gioHang.Count; i++)
            {
                int gia = Convert.ToInt32(gioHang[i].GiaDaGiam);
                tongTien = tongTien + (gia * gioHang[i].SoLuong);
            }
            Session.Add("tongTien", tongTien);
            Session.Add("gioHang", gioHang);
            Session.Add("soSP", soSP);

            this.LoadComplete += new EventHandler(GioHang_LoadComplete);        
        }
        void GioHang_LoadComplete(object sender, EventArgs e)
        {
            sw.closeConnection();
        }
              
        protected void bt_capnhat_Click1(object sender, EventArgs e)  //cập nhật số lượng
        {
            string str = "";
            List<SanPhamMua> gioHang = null;
            if (Session["gioHang"] != null)
            {
                gioHang = (List<SanPhamMua>)Session["gioHang"];
                for (int i = 0; i < gioHang.Count; i++)
                {
                    str = Request.Params["soLuong" + i];
                    int soLuong = Convert.ToInt32(str);
                    gioHang[i].SoLuong = soLuong;
                }
                int tongTien = 0;
                int soSP = 0;
                for (int i = 0; i < gioHang.Count; i++)
                {
                    int gia = Convert.ToInt32(gioHang[i].GiaDaGiam);
                    tongTien = tongTien + (gia * gioHang[i].SoLuong);
                    soSP = soSP + gioHang[i].SoLuong;
                }
                Session.Add("tongTien", tongTien);
                Session.Add("soSP", soSP);
            }

        }
       
        protected void bt_muahang_Click(object sender, EventArgs e) //mua hàng có đăng nhập
        {

            resetData1();
            bt_capnhat.Enabled = false;
            bt_them.Enabled = false;
            bt_muahangnhanh.Enabled = false;
            Session.Add("dis","disabled");
            if (Session["kh"] == null) // đăng nhập
            {
                Session.Add("trangTruoc", "GioHang.aspx");
                Response.Redirect("Login.aspx");
            }

           
        }
        protected void bt_muanhanh_Click(object sender, EventArgs e)  //mua nhanh
        {
            resetData();
            bt_muahang.Enabled = false;
            bt_capnhat.Enabled = false;
            bt_them.Enabled = false;
            Session.Add("dis", "disabled");

        }
         protected void bt_guiDDH1_Click(object sender, EventArgs e) // khách hàng submit ĐĐH có đăng nhập
        {

           List<SanPhamMua> gioHang = (List<SanPhamMua>)Session["gioHang"];
            if (gioHang.Count == 0)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "alert('Không có sản phẩm nào trong giỏ hàng!');", true);
                return;
            }
            Session.Remove("kh_vl");
            KhachHang kh = (KhachHang)Session["kh"];
            int okCT1 = 0;
            //---------------------them Don Dat Hang
            DonHang ddh1 = null;
            if (Session["ddh1"] == null)
                ddh1 = new DonHang();
            else
                ddh1 = (DonHang)Session["ddh1"];
           
            ddh1.IDKhachHang = Convert.ToInt32(kh.IDKhachHang);
            ddh1.TongTien = Convert.ToInt32(Session["tongTien"]);
            string myDateTimeString = "";
            if (Request.Params["ngayGiaoHang1"].ToString() != "")
            {
                myDateTimeString = Request.Params["ngayGiaoHang1"].ToString() + " 12:00:00";  
                IFormatProvider culture = new CultureInfo("fr-Fr", true);
                DateTime dt = DateTime.ParseExact(myDateTimeString, "dd/MM/yyyy hh:mm:ss", culture, DateTimeStyles.NoCurrentDateDefault);
                if (dt < DateTime.Today) dt = DateTime.Today;
                ddh1.NgayGiao = Convert.ToDateTime(dt.Month + "/" + dt.Day + "/" + dt.Year);
            }
            else
            {
                ddh1.NgayGiao = DateTime.MinValue;
            }
            ddh1.IsStatus = 1;
            ddh1.GhiChu = StripHtml(ghiChu1.InnerText,false);
            ddh1.MaTinhTrang = "TTDH1";    //tình trạng chưa confirm
         
            ddh1.NgayDat = DateTime.Now;
            ddh1.TongKhuyenMai = 0;
            ddh1.NgayCapNhat = DateTime.Now;
            ddh1.TenNguoiNhan = "";
            ddh1.SoDienThoai = "";
            ddh1.Email = "";
            ddh1.DiaChiNhan = "";

            DonHang_DAO daoDH = new DonHang_DAO(sw.Connection);
            int okDDH1;
            if (Session["ddh1"] != null)
            {
                okDDH1 = daoDH.updateByKey(ddh1, ddh1.MaDonHang);
            }
            else
            {
                okDDH1 = daoDH.add(ddh1);
                Session.Add("ddh1", ddh1);
            }

            //---------------------------------------------------them chi tiet
            
            for (int i = 0; i < gioHang.Count; i++)
            {
                SanPhamMua sp = gioHang[i];
                ChiTietDonHang ct = new ChiTietDonHang();
                ct.MaSanPham = sp.MaSanPham;
                ct.SoLuong = sp.SoLuong;
                ct.MaDonHang = ddh1.MaDonHang;
                ct.Gia = sp.GiaDaGiam;
                ct.GiamGia = 0;
                ct.IsStatus = 1;
                ChiTietDonHang_DAO daoCT = new ChiTietDonHang_DAO(sw.Connection);
                int okDelete = daoCT.deleteByKey(ct.MaDonHang);
                okCT1 = daoCT.add(ct);
            }
            if ((okDDH1 >0) && (okCT1 > 0))
            {
                
                String url = "ThongTinMuaHang.aspx?maDonHang=" + ddh1.MaDonHang;
                Session.Remove("soSP");
                Session.Remove("dis");
                Response.Redirect(url);
                return;
            }
            else
                ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "alert('Đặt hàng không thành công!');", true);
        }
       
      
        protected void bt_them_Click(object sender, EventArgs e)
        {
            Session.Remove("maSanPham");
            Response.Redirect("ShowSanPham.aspx?action=advSearch");
        }

        protected void kh_Submit_Click(object sender, EventArgs e)  //submit đơn hàng mua nhanh
        {
            if (!Page.IsValid)
            {
                Session["vi"] = "visible";
                return;
            }
            kh_ccJoin.ValidateCaptcha(kh_sCode.Text);
            if (!kh_ccJoin.UserValidated)
            {
                kh_thongbao.Text = "Mã bảo vệ chưa chính xác, vui lòng nhập lại.";
                Session["vi"] = "visible";
                return;
            }
            int okCT = 0;
            Session.Remove("kh");
          
             List<SanPhamMua> gioHang =  (List<SanPhamMua>)Session["gioHang"];
                if(gioHang.Count ==0)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "alert('Không có sản phẩm nào trong giỏ hàng!');", true);
                    return;
                }

   //--------------------------------------------thêm khách hàng
                int okthemKH;

                KhachHang kh_vl = null;
                KhachHang_DAO daoKH = new KhachHang_DAO(sw.Connection);

                if (Session["kh_vl"] != null)
                {
                    kh_vl = (KhachHang)Session["kh_vl"];
                    kh_vl.IDKhachHang = Convert.ToInt32(kh_vl.IDKhachHang);
                    kh_vl.HoTen = StripHtml(kh_ten.Text, false);
                    kh_vl.Email = "khachvanglai" + kh_vl.IDKhachHang+"@gmail.com"; //StripHtml(kh_email.Text, false);
                    kh_vl.DiaChi = StripHtml(kh_address.Text, false);
                    kh_vl.SoDienThoai = StripHtml(kh_phone.Text, false);
                    kh_vl.NgaySinh = Function.Func.MinValue_SmallDatetime();
                    kh_vl.NgayTao = DateTime.Now;
                    kh_vl.Phai = "";
                    kh_vl.MatKhau = "noPass";
                    okthemKH = daoKH.updateByKey(kh_vl, kh_vl.IDKhachHang);

                }
                else
                {
                    kh_vl = new KhachHang();
                    kh_vl.HoTen = StripHtml(kh_ten.Text, false);
                    kh_vl.DiaChi = StripHtml(kh_address.Text, false);
                    kh_vl.SoDienThoai = StripHtml(kh_phone.Text, false);
                    kh_vl.NgaySinh = Function.Func.MinValue_SmallDatetime();
                    kh_vl.NgayTao = DateTime.Now;
                    kh_vl.Phai = "";
                    kh_vl.MatKhau = "noPass";
                    kh_vl.IDKhachHang = daoKH.createIDKhachHang();
                    kh_vl.Email = "khachvanglai" + kh_vl.IDKhachHang + "@gmail.com";// StripHtml(kh_email.Text, false);
                    okthemKH = daoKH.add(kh_vl);
                    Session.Add("kh_vl", kh_vl);

                }


                //--------------------------------------------------them Don Dat Hang
                DonHang ddh = null;
                if (Session["ddh"] == null)
                    ddh = new DonHang();
                else
                    ddh = (DonHang)Session["ddh"];

                ddh.TongTien = Convert.ToInt32(Session["tongTien"]);

                string myDateTimeString = "";
                if (Request.Params["kh_ngaygiao"].ToString() != "")
                {
                    /*myDateTimeString = Request.Params["kh_ngaygiao"].ToString() + " 00:00:01";
                    IFormatProvider culture = new CultureInfo("fr-Fr", true);
                    DateTime dt = DateTime.ParseExact(myDateTimeString, "dd/MM/yyyy hh:mm:ss", culture, DateTimeStyles.NoCurrentDateDefault);
                    if (dt < DateTime.Today) dt = DateTime.Today;
                    ddh.NgayGiao = Convert.ToDateTime(dt.Month + "/" + dt.Day + "/" + dt.Year);*/
                    myDateTimeString = Request.Params["kh_ngaygiao"].ToString();
                    DateTime dt = Function.Func.convertDateTimeToString(myDateTimeString);
                    if (dt < DateTime.Today) dt = DateTime.Today;
                    ddh.NgayGiao = dt;
                }
                else
                {
                    ddh.NgayGiao = DateTime.MinValue;
                }
                ddh.GhiChu = StripHtml(kh_ghichu.InnerText, false);
                ddh.MaTinhTrang = "TTDH1";    //tình trạng chưa confirm
                ddh.IsStatus = 1;
                ddh.NgayDat = DateTime.Now;
                ddh.TongKhuyenMai = 0;
                ddh.NgayCapNhat = DateTime.Now;
                ddh.TenNguoiNhan = "";
                ddh.SoDienThoai = "";
                ddh.Email = "";
                ddh.DiaChiNhan = "";
                ddh.IDKhachHang = Convert.ToInt32(kh_vl.IDKhachHang);

                DonHang_DAO daoDH = new DonHang_DAO(sw.Connection);
                int okDDH;
                if (Session["ddh"] != null)
                {
                    okDDH = daoDH.updateByKey(ddh, ddh.MaDonHang);
                }
                else
                {
                    okDDH = daoDH.add(ddh);
                    Session.Add("ddh", ddh);
                }

                //-----------------------------------------------------them chi tiet
               
                for (int i = 0; i < gioHang.Count; i++)
                {
                    SanPhamMua sp = gioHang[i];
                    ChiTietDonHang ct = new ChiTietDonHang();
                    ct.MaSanPham = sp.MaSanPham;
                    ct.SoLuong = sp.SoLuong;
                    ct.MaDonHang = ddh.MaDonHang;
                    ct.Gia = sp.GiaDaGiam;
                    ct.GiamGia = 0;
                    ct.IsStatus = 1;
                    ChiTietDonHang_DAO daoCT = new ChiTietDonHang_DAO(sw.Connection);
                    int okDelete = daoCT.deleteByKey(ct.MaDonHang);
                    okCT = daoCT.add(ct);
                }
                if ((okthemKH > 0) && (okDDH > 0) && (okCT > 0))
                {
                    String url = "ThongTinMuaHang.aspx?maDonHang=" + ddh.MaDonHang;
                    Session.Remove("soSP");
                    Session.Remove("dis");
                    Response.Redirect(url);
                    return;
                }
                else
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "alert('Đặt hàng không thành công!');", true);
            

        }

        protected void kh_Cancel_Click(object sender, EventArgs e)
        {
            resetData();

        }
        public static string StripHtml(string html, bool allowHarmlessTags)
        {
            if (html == null || html == string.Empty)
                return string.Empty;

            if (allowHarmlessTags)
                return System.Text.RegularExpressions.Regex.Replace(html, "", string.Empty);

            return System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*(>|$)'", string.Empty);
        }
        private void resetData()
        {
            Session["vi"] = "visible";
            Session["vi_kq"] = "hidden";
             kh_ten.Text ="";
            // kh_email.Text="";
             kh_address.Text ="";
             kh_phone.Text= "";
             kh_ghichu.InnerText = "";
   
        }
        private void resetData1()
        {
            ghiChu1.InnerText = "";
            Session["vi_kq"] = "visible";
            Session["vi"] = "hidden";

        }

        protected void bt_nhaplai1_Click(object sender, EventArgs e)
        {
            // reset
            resetData1();
        }

       /* protected void Email_CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;
            KhachHang_DAO daoKH = new KhachHang_DAO(sw.Connection);
            KhachHang k = daoKH.checkEmail(kh_email.Text.Trim());
            if (k == null) args.IsValid = true;
            

       }*/
    }
}